<?php
require 'config.php';
require 'theme.php';

// Get page content
function twitter_page($twitterid, $page, &$content, $userpwd = false) {
	$url = TWITTER_API . 'statuses/user_timeline.json?screen_name=' . $twitterid . '&page=' . $page;
	$ch = curl_init($url);
	if ($userpwd) {
		curl_setopt($ch, CURLOPT_USERPWD, $userpwd);
	}
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	curl_setopt($ch, CURLOPT_USERAGENT, 'tbackup');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	$response = curl_exec($ch);
	$response_info = curl_getinfo($ch);
	curl_close($ch);
	
	$ret = intval($response_info['http_code']);
	switch ($ret) {
		case 200:
			$json = json_decode($response);
			if ($json) {
				$content = $json;
			} else {
				$content = $response;
			}
			break;
		case 401:
			break;
		case 0:
			break;
		default:
			$result = json_decode($response);
			$result = $result->error ? $result->error : $response;
			if (strlen($result) > 500) $result = 'Something broke.';
			$content = $result;
			break;
	}
	
	return $ret;
}

function twitter_timeline($content) {
	$output = array();
	if (!is_array($content) && !is_array($content->results)) return $output;
	foreach ($content as $status) {
		$new = $status;
		if ($new->retweeted_status) {
			$retweet = $new->retweeted_status;
			unset($new->retweeted_status);
			$retweet->retweeted_by = $new;
			$new = $retweet;
		}
		$new->from = $new->user;
		unset($new->user);
		$output[(string) $new->id] = $new;
	}
	
	return $output;
}

// Save data to csv
function twitter_persist($file, $content) {
	$feed = twitter_timeline($content);
	if (count($feed) == 0) return false;
	
	foreach ($feed as $status) {
		$date = strtotime($status->created_at);
		$datestr = date('Y-m-d H:i:s', $date);
		$text = iconv('UTF-8', CHARSET, $status->text);
		$text = str_replace('"', '""', $text);
		
		fwrite($file, $datestr . ',' . $status->id . ',"' . $text . '"' . chr(13) . chr(10));
	}
	
	return true;
}

function twitter_process() {
	$userpwd = false;
	
	if ($_POST['username']) {
		$userpwd = $_POST['username'] . ':' . $_POST['password'];
	}
	
	$frompage = intval($_POST['frompage']);
	$topage = false;
	
	if ($_POST['topage']) {
		$topage = intval($_POST['topage']);
	}
	
	$twitterid = $_POST['twitterid'];
	$filename = DATA_FOLDER . $twitterid . '.' . $frompage . '-';
	if ($topage) {
		$filename .= $topage . '.csv';
	} else {
		$filename .= 'end.csv';
	}
	
	if (!file_exists(DATA_FOLDER)) {
		mkdir(DATA_FOLDER);
	}

	$file = fopen($filename, 'w+');
	if (!$file) {
		theme('error', '<p>'.__("Error: Failed to create data file.") . '</p>');
	}
	fwrite($file, 'Time,Id,Text' . chr(13) . chr(10));
	
	$msg = 'Success';
	$breakFor = false;
	
	for ($page = $frompage; !$topage || $topage && $page <= $topage; $page++) {
		$ret = twitter_page($twitterid, $page, $content, $userpwd);
		switch ($ret) {
			case 200:
				if (!twitter_persist($file, $content)) $breakFor = true;
				break;
			case 401:
				$breakFor = true;
				$msg = '<p>'.__("Error: Login credentials incorrect.") . '</p>';
				if ($page == $frompage) {
					fclose($file);
					theme('error', $msg);
				}
				break;
			case 0:
				$breakFor = true;
				$msg = '<h3>Twitter timed out</h3><p>TBackup gave up on waiting for Twitter to respond. They\'re probably overloaded right now, try again in a minute.</p>';
				if ($page == $frompage) {
					fclose($file);
					theme('error', $msg);
				}
				break;
			default:
				$breakFor = true;
				$msg = "<h3>".__("An error occured while calling the API")."</h3><p>{$ret}: {$content}</p>";
				if ($page == $frompage) {
					fclose($file);
					theme('error', $msg);
				}
		}
		if ($breakFor) break;	// Break for
	}
	fclose($file);
	
	$page--;
	if (!$topage) {
		$newfilename = str_replace('-end', '-' . $page, $filename);
		rename($filename, $newfilename);
	}
	
	header('location: download.php?frompage=' . $frompage . '&topage=' . $page . '&msg=' . urlencode($msg));
}

// maximum execution time in seconds
set_time_limit (24 * 60 * 60);

date_default_timezone_set('Asia/Chongqing');

// Do process
twitter_process();
?>